package com.example.servlet;

import com.example.dao.GuitarDao;
import com.example.entity.Guitar;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/guitar")
public class GuitarServlet extends HttpServlet {
    private GuitarDao guitarDao = new GuitarDao();
    private Gson gson = new Gson();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if ("list".equals(action)) {
            List<Guitar> guitars = guitarDao.findAll();
            request.setAttribute("guitars", guitars);
            request.getRequestDispatcher("guitar.jsp").forward(request, response);
        } else if ("get".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            Guitar guitar = guitarDao.findById(id);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(gson.toJson(guitar));
        } else if ("delete".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            guitarDao.delete(id);
            response.sendRedirect("guitar?action=list");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        
        if ("add".equals(action)) {
            String brand = request.getParameter("brand");
            String type = request.getParameter("type");
            String manufacturer = request.getParameter("manufacturer");
            double price = Double.parseDouble(request.getParameter("price"));
            
            Guitar guitar = new Guitar(brand, type, manufacturer, price);
            guitarDao.add(guitar);
        } else if ("edit".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            String brand = request.getParameter("brand");
            String type = request.getParameter("type");
            String manufacturer = request.getParameter("manufacturer");
            double price = Double.parseDouble(request.getParameter("price"));
            
            Guitar guitar = new Guitar(brand, type, manufacturer, price);
            guitar.setId(id);
            guitarDao.update(guitar);
        }
        
        response.sendRedirect("guitar?action=list");
    }
} 